﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using static QntPlatform.Strategy.TvCmdHandler;
using QntPlatform.Strategy.CmdCtrl;

namespace QntPlatform.Strategy.CmdCtrl
{
 /// <summary>
 /// 趋势做单，只添加固定止损，不设止盈，
 /// </summary>
    public class BuyStop: StrategyPart, ICmdCtrl
    {


        public BuyStop(StrategyBase parent):base(parent)
        {
 

        }
        TrendSet trendSet;
        public int getTrend(int period)
        {
            if (trendSet == null)
            {
                 trendSet = TrendSet.GetContextTrendSet(period, SysFun.GetRobotContext());
            }
            if (trendSet == null)
                return 0;
            return trendSet.GetTrend(period);
        }
        public void signSync(string cmd)
        {
            var info =SysFun.ParseTo<Info>(cmd);
            var trend = getTrend(info.Period);
            if (info.Direction == SideDirection.Buy&&(trend==2||trend==1))
            {
                InBuy(info);
            }
            else if (info.Direction == SideDirection.Sell && (trend == 2 || trend == -1))
            {
                InBuy(info, false);
            }
            else
            {
                log.Info("命令未处理",new { cmd,trend});
            }
        }
        public void InBuy(Info info, bool isLong = true)
        {
            //buy
            var account = Exchange.GetAccountAsync();
            var tck = Exchange.GetTickerAsync();
            var nowPrice = tck.Result.Buy;
            var buyAmount = account.Result.Balance * 0.05m * 20 / nowPrice;
            log.Debug("交易准备信息", new { account.Result.Balance, nowPrice });
            var id = isLong ? Exchange.BuyAsync( buyAmount) : Exchange.SellAsync(-1, buyAmount);
            var auto = new AutoSellOrder();
            auto.SourcePrice = nowPrice;
            //auto.ProfitPrices = cmdVal.sells;
            auto.SourceOrderId = id.Result;
            auto.SourceAmount = buyAmount;
            auto.Amount = buyAmount;
            auto.Direction = isLong ? SideDirection.CloseBuy : SideDirection.CloseSell;
            if (info.StopLoss is null)
            {
                auto.StopLossPrice = isLong ? nowPrice * 0.95m : nowPrice * 1.05m;
                log.Debug("止损为空，固定比例计算", new { auto.StopLossPrice});
            }
            else
            {
                auto.StopLossPrice =info.StopLoss.Value;
            }
            auto.HandlerType = nameof(BuyStop); // this.GetType().Name;
            var fun = new MiddleGuoup<Ticker>()
                .AddUse(new StopLoss(auto, this).Execute)
                .Bulid();
              tc = (p1, p2) => fun.Invoke(p2);
            Exchange.TickerChangeEvent += tc;
            log.Debug("突破压力，交易完成，添加止损：", auto);
        }
        EventHandler<Ticker> tc;
        public override void OnExit(Exception ex = null)
        {
            Exchange.TickerChangeEvent -= tc;
        }
        public bool AutoOutHandle(Ticker tck,AutoSellOrder autoSellOrder) {
            if (ISysFun.calcUnitProfit(tck.Buy, autoSellOrder.StopLossPrice,autoSellOrder.Direction== SideDirection.CloseBuy) <0)
            {
                execTrade(autoSellOrder.Direction, autoSellOrder.Amount);
                return true;
            }
            return false;
        }
        ILog log = Log.Default();
      
        public override void MainFun()
        {
            
        }

        public bool Execute(CmdContext context = null)
        {
             var info =SysFun.ParseTo<Info>(context.Cmd.Value);
            var trend = getTrend(info.Period);
            if (trend is  1 or -1 or 2)
            { }
            else return true;
                if (info.Direction == SideDirection.Buy&&trend!=-1)
            {
                InBuy(info);
            }
            else if (info.Direction == SideDirection.Sell&&trend!=1)
            {
                InBuy(info, false);
            }else{
                log.Warn("错误交易方向",context.CmdStr);
            }
            return true;
        }

        public List<Info> TmpInfo = new List<Info>();

        public class Info
        {
            public SideDirection Direction { get; set; }
            public decimal? StopLoss { get; set; }
            public int Period { get; set; }
        }
    }
}
